package com.scpii.api.common.auth.token;

import java.io.Serializable;
import java.util.Date;

import com.scpii.api.domain.auth.UsersInfoDetails;

public class DefaultAccessToken implements AuthAccessToken, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5217567033875387084L;

	private String value;

	private Date expiration;

	private AuthRefreshToken refreshToken;

	private UsersInfoDetails user;

	public DefaultAccessToken(String value) {
		this.value = value;
	}

	public DefaultAccessToken(AuthAccessToken accessToken) {
		this(accessToken.getValue());
		setRefreshToken(accessToken.getRefreshToken());
		setExpiration(accessToken.getExpiration());
		setUsersInfoDetails(accessToken.getUsersInfoDetails());
	}

	public DefaultAccessToken setValue(String value) {
		DefaultAccessToken result = new DefaultAccessToken(this);
		result.value = value;
		return result;
	}

	public DefaultAccessToken setValue(String value, UsersInfoDetails user) {
		DefaultAccessToken result = new DefaultAccessToken(this);
		result.value = value;
		result.user = user;
		return result;
	}

	@Override
	public boolean isExpired() {
		return expiration != null && expiration.before(new Date());
	}

	@Override
	public Date getExpiration() {
		return expiration;
	}

	@Override
	public int getExpiresIn() {
		return expiration != null ? Long.valueOf(
				(expiration.getTime() - System.currentTimeMillis()) / 1000L)
				.intValue() : 0;
	}

	@Override
	public String getValue() {
		return value;
	}

	@Override
	public AuthRefreshToken getRefreshToken() {
		return refreshToken;
	}

	public void setRefreshToken(AuthRefreshToken refreshToken) {
		this.refreshToken = refreshToken;
	}

	protected void setExpiresIn(int delta) {
		setExpiration(new Date(System.currentTimeMillis() + delta));
	}

	public void setExpiration(Date expiration) {
		this.expiration = expiration;
	}

	public void setUsersInfoDetails(UsersInfoDetails usersInfoDetails) {
		this.user = usersInfoDetails;
	}

	@Override
	public UsersInfoDetails getUsersInfoDetails() {
		return user;
	}
}
